package com.tangyuan.video.service.impl;

import com.aliyun.oss.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.common.util.*;
import com.tangyuan.common.util.gaodemap.GaodeMapUtil;
import com.tangyuan.model.*;
import com.tangyuan.video.mapper.MusicMapper;
import com.tangyuan.video.mapper.VideoMapper;
import com.tangyuan.video.mapper.VideoPublishMapper;
import com.tangyuan.video.service.IMusicService;
import com.tangyuan.video.service.VideoPublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class VideoPublishServiceImpl implements VideoPublishService {
    @Autowired
    VideoPublishMapper videoPublishMapper;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private IMusicService musicService;

    public Result getMusicList(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Music> list = videoPublishMapper.getMusicList();
        Map map = new HashMap();
        map.put("music", new PageInfo<>(list));
        return Result.ok(map);
    }


    @Override
    public Result publishLittleVideo(MultipartFile image,
                                     MultipartFile video,
                                     String title,
                                     String place,
                                     Integer tag,
                                     String token) {
        //上传视频到阿里
        String videoUrl = VideoOSSUtils.upload(video, FileNameUtil.getMp4Name());
        //上传头像到阿里
        String imageUrl = PictureOSSUtils.upload(image, FileNameUtil.getPngName());

        User user = CommStatus.getUser(token);
        VideoPublish videoPublish = new VideoPublish();
        videoPublish.setTitle(title);
        videoPublish.setImage(imageUrl);
        videoPublish.setVideo(videoUrl);
        videoPublish.setPlace(place);
        videoPublish.setTag(tag);
        videoPublish.setUserId(user.getId());
        videoPublish.setPublisher(user.getName());
        videoPublish.setPublishId(user.getId());
        videoPublish.setUserId(user.getId());
        videoPublish.setPublishDate(DateUtil.changeLocalDateTimeToDate(LocalDateTime.now()));
        videoPublishMapper.publishLittleVideo(videoPublish);
        return Result.ok();
    }

    @Override
    public Result publishLittleVideo(MultipartFile videoSource, String title, String address, BigDecimal longitude, BigDecimal latitude, String token, String littleVideoUrl, Integer categoryId) {
        User user = CommStatus.getUser(token);
        if (user == null) {
            return Result.build("", ResultCodeEnum.FAIL_LOGIN);
        }
        //上传视频到阿里
        if (StringUtils.isBlank(littleVideoUrl)) {
            littleVideoUrl = VideoOSSUtils.upload(videoSource, FileNameUtil.getMp4Name());
        }
        //第一帧图片
        String imageByVideo = VideoOSSUtils.getImageByVideo(littleVideoUrl);
        Video video = new Video();
        video.setContent(littleVideoUrl);
        video.setImage(imageByVideo);
        video.setTitle(title);
        video.setAddress(address);
        video.setLongitude(longitude);
        video.setLatitude(latitude);

        //获取视频时长
        long durationBackMillis = VideoUtils.getDurationBackMillis(videoSource);
        video.setDuration(Integer.parseInt(String.valueOf(Math.round(durationBackMillis / 1000.0))));

        //通过高德解析经纬度获取城市编码
        String cityCode = GaodeMapUtil.getCityCode(longitude, latitude);
        video.setCityCode(cityCode);

        video.setPublishDate(new Date());
        video.setPublisher(user.getName());
        video.setUserId(user.getId());
        video.setPublisherIcon(user.getHeadImage());
        video.setStatus(1);
        video.setUploadType(1);
        video.setCreateTime(new Date());
        video.setCreateBy(user.getName());
        video.setUpdateTime(new Date());
        video.setUpdateBy(user.getName());
        video.setIsDeleted(0);
        video.setScope(0);
        video.setType(2);
        video.setCategoryId(categoryId);
        videoMapper.insert(video);
        return Result.ok();
    }

    @Override
    public Result publishLittleMusic(MultipartFile musicFile, MultipartFile image, String singer, String title, String token) {
        User user = CommStatus.getUser(token);
        //上传音频到阿里
        String musicUrl = VideoOSSUtils.upload(musicFile, FileNameUtil.getMp3Name());
        //上传头像到阿里
        String imageUrl = PictureOSSUtils.upload(image, FileNameUtil.getPngName());

        Music music = new Music();
        music.setTitle(title);
        music.setImage(imageUrl);
        music.setContent(musicUrl);
        music.setCreateTime(new Date());
        music.setSinger(singer);
        music.setUserId(user.getId());
        music.setUserName(user.getName());
        music.setPublishDate(new Date());
        musicMapper.insert(music);

        return Result.ok();
    }


    @Override
    public Result insertMusic(String token, String folderPath) {
        User user = CommStatus.getUser(token);
        if (user == null) {
            return Result.build("", ResultCodeEnum.FAIL_LOGIN);
        }
        if (StringUtils.isBlank(folderPath)) {
            return Result.build("", ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }

        String endpoint = "oss-cn-qingdao.aliyuncs.com";
        String accessKeyId = "LTAI5tQZMYYEwFYBC8vYCkPR";
        String accessKeySecret = "FKqXvgNCC5ivMFLcqZHh0TXF7u0iyF";
        String bucketName = "shengtangfeng1";

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 遍历指定文件夹下的所有.mp3文件
            Path dirPath = Paths.get(folderPath);
            List<Path> mp3Paths = Files.list(dirPath)
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".mp3"))
                    .collect(Collectors.toList());

            int numThreads = Runtime.getRuntime().availableProcessors();
            ExecutorService executor = Executors.newFixedThreadPool(numThreads);

            // 使用同步列表保证线程安全
            List<Music> musicList = Collections.synchronizedList(new ArrayList<>());

            List<Future<?>> futures = new ArrayList<>();
            for (Path path : mp3Paths) {
                futures.add(executor.submit(() -> {
                    String objectKey = dirPath.relativize(path).toString();

                    try (FileInputStream fis = new FileInputStream(path.toFile())) {
                        String mp3Name = FileNameUtil.getMp3Name();
                        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, mp3Name, fis);
                        ObjectMetadata metadata = new ObjectMetadata();
                        metadata.setContentType("audio/mpeg");
                        metadata.setHeader("x-oss-force-download", false);
                        putObjectRequest.setMetadata(metadata);
                        ossClient.putObject(putObjectRequest);
                        String[] parts = objectKey.split("\\.");
                        if (parts.length > 0) {
                            objectKey = parts[0];
                        }
                        String prefix = objectKey.substring(0, 6);
                        String rest = objectKey.substring(7);
                        String objectUrl = "https://" + bucketName + "." + endpoint + "/" + mp3Name;
                        Music music = new Music();
                        music.setTitle(rest);
                        music.setSinger(prefix);
                        music.setImage("https://shengtangfeng1.oss-cn-qingdao.aliyuncs.com/2024-04-17T11:10:12.367c479477c88469c5869b55978.png");
                        music.setContent(objectUrl);
                        music.setUserId(user.getId());
                        music.setUserName(user.getName());
                        music.setCreateTime(new Date());
                        music.setPublishDate(new Date());
                        music.setUpdateTime(new Date());

                        // 确保添加操作是线程安全的
                        synchronized (musicList) {
                            musicList.add(music);
                        }
                    } catch (Exception e) {
                        System.err.println("Failed to upload " + path + ": " + e.getMessage());
                    }
                }));
            }

            // 等待所有任务完成
            executor.shutdown();
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

            musicService.saveBatch(musicList);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        return Result.ok();
    }

}
